package com.shouxin.attendance.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shouxin.attendance.R;
import com.shouxin.attendance.constants.CommonConstants;
import com.shouxin.attendance.database.model.Baby;
import com.shouxin.attendance.database.model.Custody;

public class BabyInfoView extends FrameLayout {

	private final Timeout mTimeout = new Timeout();
	private ImageView mHead;
	private TextView mPortText;
	private TextView mBabyInfo;

	public BabyInfoView(Context context) {
		this(context, null);
	}

	public BabyInfoView(Context context, AttributeSet attrs) {
		super(context, attrs);
		inflate(getContext(), R.layout.layout_baby_info, this);
		initView();

		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BabyInfoView);
		String portName = a.getString(R.styleable.BabyInfoView_port_name);
		a.recycle();
		mPortText.setText(portName);
	}

	private void initView() {
		mHead = (ImageView) findViewById(R.id.iv_head);
		mPortText = (TextView) findViewById(R.id.tv_port);
		mBabyInfo = (TextView) findViewById(R.id.tv_baby_info);
	}

    public void setBabyInfo(int state, Baby baby) {
        mTimeout.cancel();
		ImageLoader.getInstance().displayImage(baby.getHead(), mHead);
	    String className = "";
	    if (baby.getClazz() != null) {
		    className = baby.getClazz().getName();
	    }
	    mBabyInfo.setText(className + baby.getName() + (state == CommonConstants.POST_ENTRY ? "入校" : "离校"));
		mTimeout.start();
	}

	public void setCustody(Custody custody) {
		mTimeout.cancel();
		ImageLoader.getInstance().displayImage(custody.getHead(), mHead);
		mTimeout.start();
	}

	public void resetViews() {
		mBabyInfo.setText("");
		mHead.setImageResource(R.mipmap.default_photo);
	}

	private class Timeout extends CountDownTimer {

		private Timeout() {
			super(10000, 10000);
		}

		@Override
		public void onTick(long millisUntilFinished) {
		}

		@Override
		public void onFinish() {
			resetViews();
		}
	}
}
